import java.net.Socket;
import java.io.*;

public class TCPLink {
    private final String SERVER_HOST;
    private final int SERVER_PORT;
    private Socket socket;
    private BufferedReader input;
    private PrintWriter output;

    public TCPLink() {
        SERVER_HOST = "127.0.0.1";
        SERVER_PORT = 65525;
    }

    public TCPLink(String host, int port) {
        SERVER_HOST = host;
        SERVER_PORT = port;
    }

    public void connect() throws IOException {
        socket = new Socket(SERVER_HOST, SERVER_PORT);// 与服务器建立 Socket
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        output = new PrintWriter(socket.getOutputStream());
    }

    public void println(String s) {
        output.println(s);
        output.flush();
        System.out.println("send\t=>\t" + s);
    }

    public String readLine() throws IOException {
        String read = input.readLine();
        System.out.println("receive\t<=\t" + read);
        println("received");
        return read;
    }

    public String readLine(String reply) throws IOException {
        String read = input.readLine();
        println(reply);
        return read;
    }

    public void close() {
        try {
            socket.close();
            input.close();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}